package cn.geekyspace.scanhive;

import cn.geekyspace.scanhive.serial.manager.PLCSerialPortManager;
import cn.geekyspace.scanhive.serial.manager.ScannerSerialPortManager;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.IOException;
import java.util.Objects;

@Slf4j
public class ScanHiveJavaFXApplication extends Application {
    private ConfigurableApplicationContext context;

    @Override
    public void init() {
        context = new SpringApplicationBuilder(ScanHiveApplication.class).run();
    }

    @Override
    public void start(Stage primaryStage) throws IOException {
        // JavaFX 界面启动逻辑
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/View.fxml"));
        // 使用 Spring 管理控制器
        fxmlLoader.setControllerFactory(context::getBean);
        // 16:10
        Scene scene = new Scene(fxmlLoader.load(), 1000, 650);
        primaryStage.setTitle("清洗机系统");
        primaryStage.getIcons().add(new Image(Objects.requireNonNull(getClass().getResource("/img/geeky.png")).toExternalForm()));
        primaryStage.initStyle(StageStyle.DECORATED);
        primaryStage.setScene(scene);

        // 设置关闭事件监听器
        primaryStage.show();
    }



    @Override
    public void stop() {
        log.info("正在关闭 JavaFX 应用程序和 Spring Boot...");
        releaseResources();
        log.info("应用程序已成功关闭。");
    }

    private void releaseResources() {
        try {
            // 释放扫码枪串口资源
            ScannerSerialPortManager scannerSerialPortManager = context.getBean(ScannerSerialPortManager.class);
            scannerSerialPortManager.releaseResources();
            log.info("扫码枪资源已释放。");

            // 释放PLC串口资源
            PLCSerialPortManager plcSerialPortManager = context.getBean(PLCSerialPortManager.class);
            plcSerialPortManager.closePort();
            log.info("PLC资源已释放。");
        } catch (Exception e) {
            log.error("释放资源时发生异常：", e);
        } finally {
            if (context != null) {
                context.close();
                log.info("Spring Boot 上下文已关闭。");
            }
        }
    }

}
